package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.UserLike;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class UserLikeApiImpl implements UserLikeApi{
    @Autowired
    private MongoTemplate mongoTemplate;

    //保存或修改喜欢信息
    @Override
    public Boolean saveOrUpdate(Long userId, Long loveUserId, boolean isLove) {
        try {
            //查询表中是否有喜欢信息
            Query query = Query.query(Criteria.where("userId").is(userId).and("likeUserId").is(loveUserId));
            //
            if (mongoTemplate.exists(query,UserLike.class)){
                Update update = Update.update("isLike",isLove).set("updated",System.currentTimeMillis());
                mongoTemplate.updateFirst(query,update,UserLike.class);
            }else {
                //没有喜欢信息 则需要保存信息
                UserLike userLike = new UserLike();
                userLike.setUserId(userId);
                userLike.setLikeUserId(loveUserId);
                userLike.setIsLike(isLove);
                userLike.setCreated(System.currentTimeMillis());
                userLike.setUpdated(System.currentTimeMillis());

                mongoTemplate.save(userLike);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    //查询喜欢我的
    @Override
    public List<UserLike> selectLove(Long userId) {
        Query query = Query.query(Criteria.where("likeUserId").is(userId).
                and("isLike").is(true));
        List<UserLike> userLikes = mongoTemplate.find(query, UserLike.class);
        return userLikes;
    }

    //查询互相喜欢
    @Override
    public List<UserLike> selectEachLove(Long userId, List<Long> ids) {
        Query query = Query.query(Criteria.where("userId").in(ids).and("likeUserId").is(userId));
        List<UserLike> userLikes = mongoTemplate.find(query, UserLike.class);
        return userLikes;
    }
}
